Page({
  data: {
    loading: true,
    loadingMore: false,
    currentFilter: 'pending',
    currentFilterName: '待审核',
    
    // 统计数据
    stats: {
      pendingCount: 0,
      approvedToday: 0,
      rejectedToday: 0
    },
    
    // 筛选标签
    filterTabs: [
      { key: 'pending', name: '待审核', count: 0 },
      { key: 'approved', name: '已通过', count: 0 },
      { key: 'rejected', name: '已拒绝', count: 0 },
      { key: 'all', name: '全部', count: 0 }
    ],
    
    // 申请列表
    applications: [],
    currentPage: 1,
    pageSize: 10,
    hasMore: false,
    
    // 拒绝弹窗
    showRejectModal: false,
    rejectData: {},
    rejectReason: '',
    canConfirmReject: false, // 是否可以确认拒绝
    quickReasons: [
      '资质不符合要求',
      '信息不完整',
      '联系方式无效',
      '专业技能不匹配',
      '服务地区超出范围',
      '重复申请'
    ]
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '审核管理'
    })
    
    this.initData()
  },

  // 初始化数据
  async initData() {
    this.setData({ loading: true })
    
    try {
      await Promise.all([
        this.loadStats(),
        this.loadApplications(true)
      ])
    } catch (error) {
      console.error('❌ 初始化数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载统计数据
  async loadStats() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'getAuditStats',
        data: {}
      })
      
      if (result.result && result.result.success) {
        const stats = result.result.data
        
        // 更新筛选标签的数量
        const filterTabs = this.data.filterTabs.map(tab => ({
          ...tab,
          count: stats[`${tab.key}Count`] || 0
        }))
        
        this.setData({
          stats: stats,
          filterTabs: filterTabs
        })
      }
    } catch (error) {
      console.error('❌ 加载统计数据失败:', error)
    }
  },

  // 加载申请列表
  async loadApplications(reset = false) {
    const { currentFilter, currentPage, pageSize } = this.data
    
    if (reset) {
      this.setData({
        applications: [],
        currentPage: 1,
        hasMore: false
      })
    }
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'getTeamApplications',
        data: {
          status: currentFilter === 'all' ? null : currentFilter,
          page: reset ? 1 : currentPage,
          pageSize: pageSize
        }
      })
      
      if (result.result && result.result.success) {
        const { applications, pagination } = result.result.data
        
        // 处理申请数据
        const processedApplications = applications.map(app => ({
          ...app,
          submitTimeText: this.formatTime(app.submitTime),
          auditTimeText: app.auditTime ? this.formatTime(app.auditTime) : '',
          specialtiesText: Array.isArray(app.specialties) ? app.specialties.join('、') : app.specialties || ''
        }))
        
        this.setData({
          applications: reset ? processedApplications : [...this.data.applications, ...processedApplications],
          currentPage: pagination.page,
          hasMore: pagination.hasMore
        })
      }
    } catch (error) {
      console.error('❌ 加载申请列表失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 切换筛选条件
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter
    const filterTab = this.data.filterTabs.find(tab => tab.key === filter)
    
    this.setData({
      currentFilter: filter,
      currentFilterName: filterTab.name,
      loading: true
    })
    
    this.loadApplications(true).finally(() => {
      this.setData({ loading: false })
    })
  },

  // 加载更多申请
  async loadMoreApplications() {
    if (this.data.loadingMore || !this.data.hasMore) return
    
    this.setData({ 
      loadingMore: true,
      currentPage: this.data.currentPage + 1
    })
    
    try {
      await this.loadApplications(false)
    } finally {
      this.setData({ loadingMore: false })
    }
  },

  // 通过申请
  approveApplication(e) {
    const { id, name } = e.currentTarget.dataset
    
    wx.showModal({
      title: '确认通过',
      content: `确定通过 "${name}" 的注册申请吗？`,
      confirmText: '通过',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.performAudit(id, 'approve', '')
        }
      }
    })
  },

  // 显示拒绝弹窗
  showRejectDialog(e) {
    const { id, name } = e.currentTarget.dataset

    console.log('🚫 显示拒绝弹窗:', name)

    this.setData({
      showRejectModal: true,
      rejectData: { id, name },
      rejectReason: '',
      canConfirmReject: false // 初始状态不能确认
    }, () => {
      console.log('✅ 弹窗状态已更新 - canConfirmReject:', this.data.canConfirmReject)
    })
  },

  // 隐藏拒绝弹窗
  hideRejectDialog() {
    console.log('❌ 隐藏拒绝弹窗')

    this.setData({
      showRejectModal: false,
      rejectData: {},
      rejectReason: '',
      canConfirmReject: false
    })
  },

  // 防止弹窗关闭（阻止事件冒泡）
  preventClose(e) {
    // 在小程序中，catchtap 已经阻止了事件冒泡，这里只需要空实现
    console.log('🛡️ 防止弹窗关闭')
  },

  // 防止触摸穿透
  preventTouchMove(e) {
    // 在小程序中，catchtouchmove 已经阻止了触摸事件穿透
    console.log('🛡️ 防止触摸穿透')
  },

  // 输入拒绝原因
  onRejectReasonInput(e) {
    const rejectReason = e.detail.value
    const canConfirmReject = rejectReason.trim().length > 0

    console.log('📝 输入拒绝原因:', rejectReason, '可确认:', canConfirmReject)

    this.setData({
      rejectReason: rejectReason,
      canConfirmReject: canConfirmReject
    })
  },

  // 选择快速原因
  selectQuickReason(e) {
    const reason = e.currentTarget.dataset.reason
    const canConfirmReject = reason.trim().length > 0

    console.log('📝 选择快速原因:', reason, '可确认:', canConfirmReject)

    this.setData({
      rejectReason: reason,
      canConfirmReject: canConfirmReject
    })
  },

  // 确认拒绝
  confirmReject() {
    const { rejectData, rejectReason, canConfirmReject } = this.data

    // 双重检查
    if (!canConfirmReject || !rejectReason.trim()) {
      wx.showToast({
        title: '请输入拒绝原因',
        icon: 'none'
      })
      return
    }

    console.log('🔍 确认拒绝申请:', rejectData.name, '原因:', rejectReason.trim())

    this.hideRejectDialog()
    this.performAudit(rejectData.id, 'reject', rejectReason.trim())
  },

  // 执行审核操作
  async performAudit(teamId, action, reason) {
    wx.showLoading({
      title: action === 'approve' ? '审核中...' : '拒绝中...',
      mask: true
    })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'auditTeamRegistration',
        data: {
          teamId: teamId,
          action: action,
          reason: reason
        }
      })
      
      wx.hideLoading()
      
      if (result.result && result.result.success) {
        wx.showToast({
          title: action === 'approve' ? '审核通过' : '已拒绝',
          icon: 'success'
        })
        
        // 刷新数据
        this.initData()
      } else {
        throw new Error(result.result?.error || '操作失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('❌ 审核操作失败:', error)
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    }
  },

  // 格式化时间
  formatTime(time) {
    if (!time) return ''
    
    const date = new Date(time)
    const now = new Date()
    const diff = now - date
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚'
    }
    
    // 小于1小时
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`
    }
    
    // 小于1天
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`
    }
    
    // 小于7天
    if (diff < 604800000) {
      return `${Math.floor(diff / 86400000)}天前`
    }
    
    // 超过7天显示具体日期
    return `${date.getMonth() + 1}月${date.getDate()}日`
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.initData().finally(() => {
      wx.stopPullDownRefresh()
    })
  }
})
